// @Author: Duanxj
// @Description:
// @Version: 1.0.0
// @Date: 2021/1/25
// @Time: 10:55

package MysqlConnect

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/jinzhu/gorm"
	"rest/until"
)

// 原生连接数据库方法
func InitDB() *sql.DB {
	cfg := until.ReturnConfig().MysqlSetting
	fmt.Println(cfg)
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		cfg.Username,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.Database,
		cfg.Charset,
	)
	fmt.Println(args, cfg.DriverName)
	db, err := sql.Open(cfg.DriverName, "root:root@tcp(localhost:3306)/gin?charset=utf8&parseTime=true")
	if err != nil {
		fmt.Println("-----数据库连接失败-----" + err.Error())
		_ = db.Close()
		panic("failed to connect database,err:" + err.Error())
	}
	return db
}

// Gorm连接数据库
func GormInitDB() *gorm.DB {
	cfg := until.ReturnConfig().MysqlSetting
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		cfg.Username,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.Database,
		cfg.Charset,
	)
	db, err := gorm.Open(cfg.DriverName, args)
	if err != nil {
		fmt.Println("-----数据库连接失败-----")
		_ = db.Close()
		panic("failed to connect database,err:" + err.Error())
	}
	return db
}

// xorm连接数据库

type XormEngine struct {
	*xorm.Engine
}

func XormInitDB() (*XormEngine, error) {
	cfg := until.ReturnConfig().MysqlSetting
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		cfg.Username,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.Database,
		cfg.Charset,
	)
	fmt.Println(args)
	engine, err := xorm.NewEngine(cfg.DriverName, args)
	if err != nil {
		fmt.Println("启动xorm失败")
		return nil, err
	}
	// 开启查询时间 sql语句显示
	engine.ShowExecTime(true)
	engine.ShowSQL(true)

	orm := new(XormEngine)
	orm.Engine = engine
	return orm, nil
}

// 建表操作
//err = engine.Sync2(new(model.SmCode))
//if err != nil {
//return nil ,err
//}
